package main

import (
	"cat-collage-backend/internal/config"
	"cat-collage-backend/internal/handler"
	"cat-collage-backend/internal/repository/mysql"
	"cat-collage-backend/internal/repository/redis"
	"cat-collage-backend/internal/repository/storage"
	"github.com/gin-gonic/gin"
	redis2 "github.com/go-redis/redis/v8"
	"gorm.io/gorm"
	"log"
)

func main() {
	// 设置Gin模式
	gin.SetMode(gin.ReleaseMode)

	// 初始化配置，你可以根据需要添加更多配置
	cfg := config.Init()

	db, err := mysql.NewMySQLConn(cfg)
	if err != nil {
		log.Fatalf("Could not connect to MySQL: %v", err)
	}
	defer func(db *gorm.DB) {
		sqlDB, err := db.DB()
		if err != nil {
			log.Fatalf("Could not close database connection: %v", err)
		}
		if err := sqlDB.Close(); err != nil {
			log.Fatalf("Could not close database connection: %v", err)
		}
	}(db)

	log.Println("MySQL 连接")

	rdb := redis.NewRedisClient(cfg)
	defer func(rdb *redis2.Client) {
		err := rdb.Close()
		if err != nil {
			log.Fatalln(err)
		}
	}(rdb)

	log.Println("Redis 连接")

	// 初始化存储
	qiniuStorage.InitStorage(cfg)
	log.Println("存储初始化成功")
	// 创建Gin引擎
	router := gin.New()
	// 注册中间件，比如日志和恢复中间件
	router.Use(gin.Logger())
	router.Use(gin.Recovery())

	log.Println("注册中间件")
	// 设置路由
	handler.SetupRoutes(router, db)
	log.Println("启动路由")
	// 启动服务器
	router.Run(cfg.Server.Address)

	log.Println("项目初始化成功")
}
